<template>
  <div class="hawkContent">
    <hawk-breadcrumb></hawk-breadcrumb>

    <div>
      <el-row :gutter="14" :style="{fontSize:'12px'}">
        <el-col :span="3" class="elCol">
          <span>姓名</span>
          <el-input placeholder="请输入姓名搜索"
                    v-model="queryForm.query.personalName"></el-input>
        </el-col>
        <el-col :span="3" class="elCol">
          <span>性别</span>
          <div>
            <el-select clearable v-model="queryForm.query.sex"
                       placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="3" class="elCol">
          <span>状态</span>
          <div>
            <el-select clearable v-model="queryForm.query.status"
                       placeholder="请选择状态">
              <el-option label="已启用" value="1"></el-option>
              <el-option label="未启用" value="0"></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="3" class="elCol">
          <span>公司</span>
          <div>
            <el-select clearable @change="getDepartments"
                       v-model="queryForm.query.companyId" placeholder="请选择公司">
              <el-option v-for="item in companyOptions" :key="item.id"
                         :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="3" class="elCol">
          <span>部门</span>
          <div>
            <el-select clearable @change="getStations"
                       v-model="queryForm.query.departmentId"
                       placeholder="请选择部门">
              <el-option v-for="item in departmentOptions" :key="item.id"
                         :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="3" class="elCol">
          <span>岗位</span>
          <div>
            <el-select clearable v-model="queryForm.query.stationId"
                       placeholder="请选择岗位">
              <el-option v-for="item in jobsOptions" :key="item.id"
                         :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </el-col>

        <el-col :span="3" class="elCol">
          <el-button type="hawkSearch" @click="init(true)">搜索</el-button>
          <el-button plain @click="reSet">重置</el-button>
        </el-col>
        <el-button @click="addUser" icon="el-icon-plus" type="primary">新增
        </el-button>
      </el-row>
    </div>

    <hawk-table v-model="multipleSelection" :page="queryForm.page"
                :table-data="tableData" :options="[
        { key: 'username', label: '用户名' },
        { key: 'password', label: '密码' },
        { key: 'nickName', label: '昵称' },
        { key: 'isEnabled', label: '是否可用' },
        { key: 'mobile', label: '手机号' },
        { key: 'email', label: '邮箱' },
        { key: 'company', label: '公司' },
        { key: 'department', label: '部门' },
        { key: 'station', label: '岗位' },
        { key: 'sex', label: '性别' },
        { key: 'roles', label: '角色' },
        { key: 'operation', label: '操作',width:'150' },
      ]">
      <template #roles='{row}'>
        <span>{{ getRolesName(row.roles)}}</span>
      </template>

      <template #company='{row}'>
        <span>{{ row.company?row.company.name:''}}</span>
      </template>
      <template #department='{row}'>
        <span>{{ row.department?row.department.name:''}}</span>
      </template>
      <template #station='{row}'>
        <span>{{ row.station?row.station.name:''}}</span>
      </template>
      <template #isEnabled='{row}'>
        <span>{{ row.isEnabled == 0 ? '可用' : '不可用'}}</span>
      </template>
      <!-- <template #roleIds='{row}'>
        <span>{{ getRoleName(row.roleIds) }}</span>
        </template> -->
      <template #isEnabled='{ row }'>
        <el-switch v-model="row.isEnabled" active-color="#13ce66"
                   inactive-color="#ff4949" :active-value="1"
                   :inactive-value="0" disabled>
        </el-switch>
      </template>
      <template #operation="{ row }">
        <span class="hawk-text-btn" @click="editUser(row)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="delUser(row)"  v-show="row.username != 'admin'" >删除</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="restPassword(row)">重置密码</span>
      </template>
    </hawk-table>

    <!-- <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click='multiDel()'>批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     v-if="tableData.length <= queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div> -->

    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="multiDel">批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="formTitle" :visible.sync="addDialogVisible"
               :close-on-click-modal="false" @close="addDialogClosed">
      <!-- 内容主题区 -->
      <el-form :model="addForm" :rules="addFormRules" label-position="right"
               ref="addFormRef" label-width="100px">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input show-password v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="addForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="公司" prop="companyId">
          <el-select clearable @change="getAddOrEditDepartments"
                     v-model="addForm.companyId" placeholder="请选择">
            <el-option v-for="item in companyOptions" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select clearable @change="getAddOrEditStations"
                     v-model="addForm.deptId" placeholder="请选择">
            <el-option v-for="item in departmentOptions" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="岗位" prop="stationId">
          <el-select clearable v-model="addForm.stationId" placeholder="请选择">
            <el-option v-for="item in jobsOptions" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isEnabled">
          <el-switch v-model="addForm.isEnabled" active-color="#13ce66"
                     inactive-color="#ff4949" :active-value="1"
                     :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item label="角色选择">
          <el-select v-model="addForm.roleIds" multiple placeholder="请选择"
                     @change="$forceUpdate()">
            <el-option v-for="item in roleOptions" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
/**
 * @author 韩玉龙
 * @description 用户管理的视图层
 * @api /moniter-host
 * @since 2021年11月3日18:03
 * @update 2021年11月3日18:04
 * @modifier 韩玉龙
 * @bug 无
 * @version v1.0.0
 */
import {
  doDelete,
  doAdd,
  doEdit,
  searchList,
  exists,
  getUserById,
  modifyPassword,
} from '@/api/system/user.js'
import {
  getAllCompany,
  getDepartmentsByCompayId,
} from '@/api/assets/dictionaries/company.js'
import { getAllDept } from '@/api/assets/dictionaries/department.js'
import {
  findStationsByDeptId,
  getAllStn,
} from '@/api/assets/dictionaries/station.js'
import { getAllRoles } from '@/api/system/role.js'
import HawkTable from '@/components/table'
import HawkBreadcrumb from '@/components/breadcrumb/Breadcrumb'
import { async } from 'q'

import { getDepartByComId } from '@/api/assets/dictionaries/department'

export default {
  components: { HawkTable, HawkBreadcrumb },
  //import引入的组件需要注入到对象中才能使用",
  data() {
    let checkUsername = async (rule, value, callback) => {
      let ret = await this.usernameRules()
      if (ret) {
        callback(new Error('角色已存在'))
      }
      // else{
      //   callback()
      // }
    }
    //这里存放数据",
    //这里存放数据",
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      formTitle: '',
      addDialogVisible: false,
      multipleSelection: [],
      total: 0,
      addForm: {
        id: '',
        username: '',
        nickName: '',
        sex: '',
        mobile: '',
        email: '',
        companyId: '',
        deptId: '',
        stationId: '',
        isEnabled: '',
        roleIds: [],
      },
      //搜索参数
      queryForm: {
        query: {
          personalName: '',
          sex: '',
          status: '',
          departmentId: '',
          companyId: '',
          stationId: '',
        },
        page: {
          current: 1,
          size: 10,
        },
      },
      searchData: {
        current: 1,
        size: 10,
        condition: {
          nickName: '',
          sex: '',
          isEnabled: '',
          deptId: '',
          stationId: '',
          companyId: '',
        },
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
          },
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
          },
          {
            validator: checkEmail,
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            required: true,
            message: '请输入电话号码',
            trigger: 'blur',
          },
          {
            validator: checkMobile,
            trigger: 'blur',
          },
        ],
        companyId: [
          {
            required: true,
            message: '请选择公司',
            trigger: 'blur',
          },
        ],
        deptId: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'blur',
          },
        ],
        stationId: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'blur',
          },
        ],
      },
      tableData: [],
      filterText: '',
      options: [
        {
          value: '男',
          label: '男',
        },
        {
          value: '女',
          label: '女',
        },
      ],
      status: [
        {
          value: 0,
          label: '未启用',
        },
        {
          value: 1,
          label: '已启用',
        },
      ],
      departmentOptions: [],
      jobsOptions: [],
      companyOptions: [],
      roleOptions: [],
      data: [
        {
          label: '同多优科技',
          children: [],
        },
      ],
      defaultProps: {
        children: 'children',
        label: 'label',
      },

      isFirstEdit: false,
    }
  },
  watch: {
    'addForm.companyId': {
      // 所选择公司发生改变时
      async handler(newValue, oldValue) {
        console.log(newValue)
        // 根据公司，获得该公司的部门
        if (!newValue) {
          this.addForm.deptId=''
          this.departmentOptions=[]
          this.addForm.stationId=''
          this.jobsOptions=[]
          return
        }
        const data = await getDepartByComId(newValue)

        console.log(data)
        this.departmentOptions = data.data

        if (this.isFirstEdit) return
        this.addForm.deptId = ''
      },
    },

    'addForm.deptId': {
      // 所选择部门发生改变时
      async handler(newValue, oldValue) {
        console.log(newValue)
        // 根据部门，获得该部门所有人
         if (!newValue) {
          this.addForm.stationId=''
          this.jobsOptions=[]
          return
        }

        // 根据 部门 ，获得 岗位
        let stationsRes = await findStationsByDeptId(this.addForm.deptId)
        this.jobsOptions = stationsRes.data

        if (this.isFirstEdit) return

        this.addForm.stationId = ''
      },
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
  //监听属性 类似于data概念",
  computed: {
    cellStyle() {
      return {
        padding: '8px 0',
      }
    },
  },
  //监控data中的数据变化",
  // watch: {

  // },
  //方法集合",
  methods: {
    // 重置密码
    async restPassword(row) {
      row.password = '123456'
      let res = await modifyPassword(row)
      this.$message({
        type: 'success',
        message: '修改成功!',
      })
      setTimeout(() => {
        this.init()
      }, 200)
    },
    // 验证用户名是否存在
    async usernameRules() {
      let res = await exists(this.addForm.username)
      console.log(res)
      if (res.code === 20000) {
        return true
      } else {
        return false
      }
    },

    getRolesName(roles) {
      // roles.reduce(item=>{
      //   return item.name+" "
      // },"")
      console.log(roles)
      let ret = ''
      roles.forEach((item) => {
        if (item) {
          ret += '/' + item.name
        }
      })
      return ret.substring(1)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // async datas() {
    //   await getTree()
    //   // 获取部门 公司  岗位 数据
    // },
    async init() {
      console.log(this.queryForm)
      this.searchData.condition.nickName = this.queryForm.query.personalName
      this.searchData.current = this.queryForm.page.current
      this.searchData.size = this.queryForm.page.size
      //this.searchData.condition.nickName = this.queryForm.personalName
      this.searchData.condition.sex = this.queryForm.query.sex
      this.searchData.condition.isEnabled = this.queryForm.query.status
      this.searchData.condition.deptId = this.queryForm.query.departmentId
      this.searchData.condition.companyId = this.queryForm.query.companyId
      this.searchData.condition.stationId = this.queryForm.stationId
      const res = await searchList(this.searchData)
      console.log(res, '---------------表格数据----')

      this.tableData = res.data.records
      this.total = res.data.total
      // const choose = await getRoles(this.queryForm)
      // this.chooseOptions = choose.data
    },
    reSet() {
      this.queryForm = this.$options.data().queryForm
      this.init()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(val)
    },
    handleSizeChange(val) {
      console.log(val)
      this.queryForm.page.size = val
      this.init()
    },
    handleCurrentChange(val) {
      console.log(val, 'handleCurrentChange')
      this.queryForm.page.current = val
      this.init()
    },

    save() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(this.addForm.id)
        if (!valid) return

        if (this.addForm.id) {
          console.log(this.addForm.id, 'edit')
          await doEdit(this.addForm)
          this.$message({
            type: 'success',
            message: '修改成功!',
          })
          this.init()
        } else {
          console.log(this.addForm, 'add')
          let ret = await doAdd(this.addForm)
          if (ret.code == 20000) {
            this.$message({
              type: 'success',
              message: '添加成功!',
            })
          }
        }
        this.init()
        this.addDialogClosed()
      })
      console.log(this.addForm)
    },
    delUser(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete([row.id])
          if (ret.code == 20000) {
            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            this.init()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },

    addUser() {
      this.addDialogVisible = true
      this.formTitle = '新增用户'
    },

    async editUser(row) {
      // if (type === 0) {
      //   this.formTitle = '添加用户'
      // } else {
      //   this.formTitle = '修改用户'
      //   this.addForm = Object.assign({}, row)
      //   console.log(this.addForm)
      // }
      // this.addDialogVisible = true

      let ret = await getUserById(row.id)
      console.log(ret)

      this.formTitle = '编辑用户'
      this.addForm = row
      this.addForm.roleIds = []

      ret.data.roles.forEach((el) => {
        this.addForm.roleIds.push(el.id)
      })

      // 获取所有部门
      this.getAllDepartments()
      // 获取所有岗位
      this.getAllStations()
      // 获取所有角色
      this.getRoles()

      this.isFirstEdit = true
      this.addDialogVisible = true

      setTimeout(() => {
        this.isFirstEdit = false
      }, 2000)
    },
    addDialogClosed() {
      this.addForm = this.$options.data().addForm
      // this.init()
      this.addDialogVisible = false
      this.departmentOptions = []

      this.$refs.addFormRef.resetFields()
    },
    multiDel() {
      console.log(this.multipleSelection)
      if (this.multipleSelection.length > 0) {
        this.$confirm('是否删除所有选中用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async () => {
          let idList = []
          for (let i = 0; i < this.multipleSelection.length; i++) {
            idList.push(this.multipleSelection[i].id)
          }

          let ret = await doDelete(idList)
          console.log(ret, '--------------ret----')

          if (ret.code == 20000) {
            let type = ''

            if (ret.data || ret.message.indexOf('成功') != -1) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }

            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.multipleSelection.length == this.tableData.length) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            console.log('-------------init---')
            this.init()
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择需要删除的数据',
        })
        return
      }
    },
    async getCompanies() {
      let companyRes = await getAllCompany()
      this.companyOptions = companyRes.data
      // let companyOption.id = data.id
      console.log(this.companyOptions)
    },
    async getDepartments() {
      console.log('111')
      // 如果公司为空，清空部门和岗位
      if (this.queryForm.query.companyId == '') {
        this.departmentOptions = []
        this.queryForm.query.departmentId = ''

        this.jobsOptions = []
        this.queryForm.query.stationId = ''

        return 
      }
      let deptRes = await getDepartmentsByCompayId(
        this.queryForm.query.companyId
      )
      console.log(deptRes)

      this.departmentOptions = deptRes.data
      this.queryForm.query.departmentId = ''
      this.queryForm.query.stationId = ''
    },
    async getStations() {
      // 如果部门是空，清空岗位
      if(this.queryForm.query.departmentId == ''){
        this.jobsOptions = []
        this.queryForm.query.stationId = ''
        return 
      }
      let stationsRes = await findStationsByDeptId(
        this.queryForm.query.departmentId
      )
      this.jobsOptions = stationsRes.data
      this.queryForm.query.stationId = ''
    },
    // async getAddOrEditCompanies() {
    //   let companyRes = await getAllCompany()
    //   this.companyOptions = companyRes.data
    //   // let companyOption.id = data.id
    //   console.log(this.companyOptions)
    // },
    async getAddOrEditDepartments() {
      console.log('111')
      let deptRes = await getDepartmentsByCompayId(this.addForm.companyId)
      this.departmentOptions = deptRes.data
      this.addForm.deptId = ''
      this.addForm.stationId = ''
    },
    async getAddOrEditStations() {
      let stationsRes = await findStationsByDeptId(this.addForm.deptId)
      this.jobsOptions = stationsRes.data
      this.addForm.stationId = ''
    },
    async getRoles() {
      let rolesRes = await getAllRoles()
      this.roleOptions = rolesRes.data
    },
    async getAllDepartments() {
      let deptRes = await getAllDept()
      this.departmentOptions = deptRes.data
    },

    async getAllStations() {
      let stationRes = await getAllStn()
      this.jobsOptions = stationRes.data
    },
  },
  //生命周期 - 创建之前",数据模型未加载,方法未加载,html模板未加载
  beforeCreate() {},
  //生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  created() {
    this.init()
    this.getRoles()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted() {
    // this.datas()
    //getAllCompany();
    this.getCompanies()
  },
}
</script>
<style lang="scss">
.hawkContent {
  width: calc(100% - 40px);
  min-height: calc(100vh - 140px);
  background: #fff;
  padding: 20px;
  border-radius: 8px;

  .inputLabel {
    font-size: 14px;
    color: #333333;
  }

  .bottom-btns {
    padding: 0 20px;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    float: none;

    &-left {
      display: flex;
      align-items: center;

      &-num {
        margin-right: 10px;
        color: #333333;
        font-size: 14px;
      }
    }
  }
}
.elCol {
  display: flex;
  // justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  span {
    width: 50px;
  }
}
.colorFont {
  color: blue;
}
.buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
}
</style>